package com.xiaoyun.xpath;

import cn.wanghaomiao.xpath.model.JXDocument;
import com.xiaoyun.xpath.handler.field.FieldHandler;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 该接口方便 与springboot整合
 * 实现 BeanPostProcessor  postProcessBeforeInitialization
 * 在bean初始化时 建立相应索引 自动映射 控制反转, 从而不用 enum 进行手动映射
 */
public class XpathHandlerStrategy extends AbstractXpathHandler {
    /**
     * private static final Map<String, FieldHandler> typeInedx = new HashMap<>();
     *
     * @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
     * <p>
     * if (!(bean instanceof FieldHandler)) {
     * return bean;
     * }
     * FieldHandler handler = (FieldHandler) bean;
     * String type = handler.type();
     * if (typeInedx.containsKey(type)) {
     * throw new IllegalStateException("重复注册");
     * }
     * log.info("Load type {} for  bean{} ", type , bean);
     * typeInedx.put(type, bean);
     * return null;
     * }
     */

    @Override
    protected <T> void typeNameBuild(String typeName, Class<T> clazz, JXDocument jxDocument, T t, Map<String, String> mappingMap, Field field) throws Exception {
        Class clazzTypeStrategy = TypeNameStrategy.getEnumType(typeName);
        if (clazz != null) {
            FieldHandler fieldHandler = (FieldHandler) Class.forName(clazzTypeStrategy.getName()).newInstance();

            fieldHandler.handlerField(clazz, jxDocument, t, mappingMap, field);
        }
    }

    private Object object;

    @Override
    public <T> T handler(String body, Object obj) {
        return this.handler(body, obj, null);
    }

    @Override
    public <T> T handler(String body, Object obj, Map<String, String> mappingMap) {
        this.object = obj;
        return (T) super.handler(body, obj.getClass(), mappingMap);
    }

    @Override
    protected <T> T getT(Class<T> clazz) {
        return (T) object;
    }
}
